package 费解的开关;

import java.util.Scanner;

public class Main {
    static char[][] g = new char[5][5];
    static char[][] backup = new char[5][5];
    static int[] dx = {0, -1, 1, 0, 0};
    static int[] dy = {0, 0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        while (T-- > 0) {
            for (int i = 0; i < 5; i++) {
                g[i] = in.next().toCharArray();
                backup[i] = g[i].clone();
            }
            int res = 10;
            for (int op = 0; op < 32; op++) {
                int step = 0;
                for (int i = 0; i < 5; i++) {
                    if ((op >> i & 1) == 1) {
                        turn(0, i);
                        step++;
                    }
                }
                for (int i = 0; i < 4; i++) {
                    for (int j = 0; j < 5; j++) {
                        if (g[i][j] == '0') {
                            turn(i + 1, j);
                            step++;
                        }
                    }
                }
                boolean dark = false;
                for (int i = 0; i < 5; i++) {
                    if (g[4][i] == '0') {
                        dark = true;
                        break;
                    }
                }
                if (!dark) {
                    res = Math.min(res, step);
                }
                for (int i = 0; i < 5; i++) {
                    g[i] = backup[i].clone();
                }
            }
            if (res > 6) {
                res = -1;
            }
            System.out.println(res);
        }
    }

    private static void turn(int x, int y) {
        for (int i = 0; i < 5; i++) {
            int a = x + dx[i];
            int b = y + dy[i];
            if (a < 0 || a >= 5 || b < 0 || b >= 5) {
                continue;
            }
            g[a][b] ^= 1;
        }
    }
}
